package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venueservice.consts.CommonConstants;
import com.eastfair.venueservice.dao.VenueDrawingCategoryAuditMapper;
import com.eastfair.venueservice.dto.VenueDrawingAuditDTO;
import com.eastfair.venueservice.dto.VenueDrawingCategoryAuditDTO;
import com.eastfair.venueservice.dto.VenueDrawingCategoryAuditHistoryDTO;
import com.eastfair.venueservice.entity.VenueDrawingCategoryAudit;
import com.eastfair.venueservice.enumeration.VenueDrawingCategoryAuditAuditStatusEnum;
import com.eastfair.venueservice.exceptioncode.VenueServiceExceptionCode;
import com.eastfair.venueservice.service.*;
import com.eastfair.venueservice.vo.VenueDrawingCategoryAuditVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 一键报馆图纸分类审核记录
 * </p>
 *
 * @author dq
 * @date 2022-10-31
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class VenueDrawingCategoryAuditServiceImpl extends SuperServiceImpl<VenueDrawingCategoryAuditMapper, VenueDrawingCategoryAudit> implements VenueDrawingCategoryAuditService {

    @Resource
    private VenueDrawingAuditService venueDrawingAuditService;

    @Resource
    private VenueDrawingCategoryAuditHistoryService venueDrawingCategoryAuditHistoryService;

    @Resource
    private ExhibitionSpaceDrawingService exhibitionSpaceDrawingService;

    @Resource
    private VenueManageVenueReportDrawingHistoryService venueManageVenueReportDrawingHistoryService;

    @Resource
    private HomeBuilderDrawingCategoryAuditService homeBuilderDrawingCategoryAuditService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<VenueDrawingCategoryAudit> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(VenueDrawingCategoryAudit model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        if (model.getAuditStatus() == null) {
            model.setAuditStatus(VenueDrawingCategoryAuditAuditStatusEnum.HAS_REPORT);
        }
        if (model.getReportTime() == null) {
            model.setReportTime(LocalDateTime.now());
        }
        return R.successDef();
    }

    @Override
    public Page<VenueDrawingCategoryAuditVO> listVenueDrawingCategoryAuditVO(PageParams<VenueDrawingCategoryAuditDTO> pageParams) {
        log.info("listVenueDrawingCategoryAuditVO - 查询一键报馆图纸分类列表VO, pageParams={}", pageParams);
        Page<VenueDrawingCategoryAudit> page = listVenueDrawingCategoryAudit(pageParams);
        Page<VenueDrawingCategoryAuditVO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        List<VenueDrawingCategoryAudit> list = page.getRecords();
        if (list == null || list.isEmpty()) {
            return voPage;
        }
        List<VenueDrawingCategoryAuditVO> voList = list
                .stream()
                .map(venueDrawingCategoryAudit -> BeanUtil.toBean(venueDrawingCategoryAudit, VenueDrawingCategoryAuditVO.class))
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public Page<VenueDrawingCategoryAudit> listVenueDrawingCategoryAudit(PageParams<VenueDrawingCategoryAuditDTO> pageParams) {
        Page<VenueDrawingCategoryAudit> pageParam = pageParams.buildPage();
        VenueDrawingCategoryAuditDTO query = pageParams.getModel();
        QueryWrapper<VenueDrawingCategoryAudit> queryWrapper = createVenueDrawingCategoryAuditQueryWrapper(query);
        return page(pageParam, queryWrapper);
    }

    @Override
    public List<VenueDrawingCategoryAudit> listVenueDrawingCategoryAudit(VenueDrawingCategoryAuditDTO query) {
        QueryWrapper<VenueDrawingCategoryAudit> queryWrapper = createVenueDrawingCategoryAuditQueryWrapper(query);
        return list(queryWrapper);
    }

    @Override
    public VenueDrawingCategoryAuditVO getVOById(Long id) {
        log.info("getVOById - id查询报馆图纸审核记录VO, id={}", id);
        VenueDrawingCategoryAudit venueDrawingCategoryAudit = getById(id);
        if (venueDrawingCategoryAudit == null) {
            return null;
        }
        return BeanUtil.toBean(venueDrawingCategoryAudit, VenueDrawingCategoryAuditVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VenueDrawingCategoryAudit saveVenueDrawingCategoryAudit(VenueDrawingCategoryAuditDTO param) {
        log.info("saveVenueDrawingCategoryAudit - 保存报馆图纸审核记录, venueDrawingCategoryAuditDTO={}", param);
        VenueDrawingCategoryAudit venueDrawingCategoryAudit = BeanUtil.toBean(param, VenueDrawingCategoryAudit.class);
        save(venueDrawingCategoryAudit);
        return venueDrawingCategoryAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitVenueDrawingCategoryAudit(VenueDrawingCategoryAuditDTO param) {
        log.info("submitVenueDrawingCategoryAudit - 提交报馆图纸审核记录, param={}", param);
        // 报馆ID移除展厅中图纸分类ID指定的报馆审核记录
        removeByVenueReportId(param.getVenueReportId(), param.getSpaceCode(), param.getDrawingId());
        // 保存报馆图纸类型审核记录
        VenueDrawingCategoryAudit venueDrawingCategoryAudit = saveVenueDrawingCategoryAudit(param);
        // 提交报馆图纸审核记录
        List<VenueDrawingAuditDTO> venueDrawingAuditList = param.getVenueDrawingAuditList();
        venueDrawingAuditService.submitBatch(venueDrawingAuditList);
        // 保存主场搭建商图纸审核记录
        homeBuilderDrawingCategoryAuditService.saveByVenueDrawingCategoryAudit(param);
        // 更新展会展厅图纸
        exhibitionSpaceDrawingService.saveBatchByVenueDrawing(venueDrawingCategoryAudit);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VenueDrawingCategoryAudit updateVenueDrawingCategoryAudit(VenueDrawingCategoryAuditDTO param) {
        log.info("updateVenueDrawingCategoryAudit - 更新报馆图纸审核记录, venueDrawingCategoryAuditDTO={}", param);
        VenueDrawingCategoryAudit venueDrawingCategoryAudit = BeanUtil.toBean(param, VenueDrawingCategoryAudit.class);
        updateById(venueDrawingCategoryAudit);
        return venueDrawingCategoryAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditVenueDrawing(VenueDrawingCategoryAuditDTO param) {
        VenueDrawingCategoryAudit venueDrawingCategoryAudit = getById(param.getId());
        if (venueDrawingCategoryAudit == null) {
            throw BizException.wrap(VenueServiceExceptionCode.VENUE_DRAWING_CATEGORY_AUDIT_NOT_EXIST);
        }
        if (!VenueDrawingCategoryAuditAuditStatusEnum.HAS_REPORT.eq(venueDrawingCategoryAudit.getAuditStatus())) {
            throw BizException.wrap(VenueServiceExceptionCode.REPORT_VENUE_SPACE_CAN_NOT_AUDIT.getCode(), "图纸已审核，不可再审核");
        }
        venueDrawingCategoryAudit.setAuditStatus(param.getAuditStatus());
        venueDrawingCategoryAudit.setAuditOpinion(param.getAuditOpinion());
        venueDrawingCategoryAudit.setAuditTime(LocalDateTime.now());
        venueDrawingCategoryAudit.setAuditUserId(param.getAuditUserId());
        venueDrawingCategoryAudit.setAuditUserName(param.getAuditUserName());
        updateById(venueDrawingCategoryAudit);
        // 保存审核历史
        CopyOptions copyOptions = CopyOptions
                .create()
                .setIgnoreProperties(CommonConstants.COMMON_IGNORE_PROPERTIES);
        VenueDrawingCategoryAuditHistoryDTO historyDTO = BeanUtil.toBean(venueDrawingCategoryAudit, VenueDrawingCategoryAuditHistoryDTO.class, copyOptions);
        venueDrawingCategoryAuditHistoryService.saveHistory(historyDTO);
        // 审核通过则更新展会展厅图纸
//        if (VenueDrawingCategoryAuditAuditStatusEnum.APPROVED.eq(venueDrawingCategoryAudit.getAuditStatus())) {
//            exhibitionSpaceDrawingService.saveBatchByVenueDrawing(venueDrawingCategoryAudit);
//        }
        return true;
    }

    @Override
    public boolean auditBatchVenueDrawing(List<VenueDrawingCategoryAuditDTO> list) {
        log.info("auditBatchVenueDrawing - 批量审核图纸, list={}", list);
        if (list == null || list.isEmpty()) {
            return true;
        }
        list.forEach(this::auditVenueDrawing);
        // 更新主场提交历史的审核记录
        venueManageVenueReportDrawingHistoryService.asyncUpdateBatchByDrawingAuditList(list);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByVenueReportId(Long venueReportId, String spaceCode, Long drawingId) {
        log.info("removeByVenueReportId - 报馆ID移除报馆审核记录, venueReportId={}, spaceCode={}, drawingId={}", venueReportId, spaceCode, drawingId);
        VenueDrawingCategoryAuditDTO param = new VenueDrawingCategoryAuditDTO();
        param.setVenueReportId(venueReportId);
        param.setSpaceCode(spaceCode);
        param.setDrawingId(drawingId);
        List<VenueDrawingCategoryAudit> list = listVenueDrawingCategoryAudit(param);
        if (list == null || list.isEmpty()) {
            return true;
        }
        return removeByIdsOfLogic(list);
    }

    private QueryWrapper<VenueDrawingCategoryAudit> createVenueDrawingCategoryAuditQueryWrapper(VenueDrawingCategoryAuditDTO query) {
        QueryWrapper<VenueDrawingCategoryAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(VenueDrawingCategoryAudit::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getExhibitionManageId() != null, VenueDrawingCategoryAudit::getExhibitionManageId, query.getExhibitionManageId())
                .eq(query.getVenueReportId() != null, VenueDrawingCategoryAudit::getVenueReportId, query.getVenueReportId())
                .eq(StrUtil.isNotBlank(query.getSpaceCode()), VenueDrawingCategoryAudit::getSpaceCode, query.getSpaceCode())
                .eq(query.getDrawingId() != null, VenueDrawingCategoryAudit::getDrawingId, query.getDrawingId())
                .like(StrUtil.isNotBlank(query.getDrawingName()), VenueDrawingCategoryAudit::getDrawingName, query.getDrawingName())
                .eq(StrUtil.isNotBlank(query.getDrawingType()), VenueDrawingCategoryAudit::getDrawingType, query.getDrawingType())
                .eq(query.getAuditStatus() != null, VenueDrawingCategoryAudit::getAuditStatus, query.getAuditStatus())
                .orderByAsc(VenueDrawingCategoryAudit::getDrawingSort)
        ;
        return queryWrapper;
    }
}
